package com.jlkf.controller;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jlkf.view.QiniuToken;
import com.jlkf.ys.qiniu.Auth;
import com.platform.server.util.HttpClientUtils;

import qiniu.happydns.util.Hex;


@Controller
@RequestMapping("/qiniu")
public class QiniuController {
	
	//private static String accessKey = "m79prQpt5bsafJGWLhW15gi_tQT_WxUSd2S8rTtX";  
	//private static String secretKey = "myvaNmFJNDDKaCOjrHTKmGboEy54nWjrmZnQvGYl";  
	private static String accessKey = "CYA2nd06bG-3ge6106lJcNC9mugAXqOXf1CW3-Qo";  
	private static String secretKey = "WwZWgqVgOlVHF7PlZHNFQ7eWs28QgQxZOaYUXx6a";  
	private static String bucket = "hqsmapp";

	/** 
     * 生成上传凭证 
	 */
	@RequestMapping(value = "/uptoken", method = RequestMethod.GET)  
	@ResponseBody 
	public Object getUploadCredential() {  
	       Auth auth = Auth.create(accessKey, secretKey);  
	       String upToken = auth.uploadToken(bucket);  
	       System.out.println(upToken);  
	       return new QiniuToken(upToken);  
	}  
	
	public Auth getAuth() {  
		return Auth.create(accessKey, secretKey);  
    } 

	 
	 
	 
	 
	 /*public ResponseEntity<Object> makeToken() {  
	    // 需要修改AK、SK、bucketName  
	    Config.ACCESS_KEY = "pRyQPoTs_lqt02zxHGyriLUufn_RXvsDTkNQnkms";  
	    Config.SECRET_KEY = "PVQYJx2eE7OdW-BwWT7soSYm0DLpusfI6zp45r9S";  
	    Mac mac = new Mac(Config.ACCESS_KEY, Config.SECRET_KEY);  
	    String bucketName = "niu8";  
	    PutPolicy putPolicy = new PutPolicy(bucketName);  
	    
	    try {  
	        String uptoken = putPolicy.token(mac);  
	        JSONObject jsonObject=new JSONObject();  
	        jsonObject.put("uptoken",uptoken);  
	        return new ResponseEntity(jsonObject, HttpStatus.SC_OK);  
	    } catch (AuthException e) {  
	        e.printStackTrace();  
	        return new ResponseEntity(null, HttpStatus.BAD_REQUEST);  
	    } catch (JSONException e) {  
	        e.printStackTrace();  
	        return new ResponseEntity(null, HttpStatus.BAD_REQUEST);  
	    }  
	}*/
	
	/**
	 * 生成资源基于CDN时间戳防盗链的访问外链
	 *
	 * @throws MalformedURLException
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException
	 */
	public static String getAntiLeechAccessUrlBasedOnTimestamp(String url, String encryptKey, int durationInSeconds)
			throws MalformedURLException, UnsupportedEncodingException, NoSuchAlgorithmException {
		URL urlObj = new URL(url);
		String path = urlObj.getPath();
		long timestampNow = System.currentTimeMillis() / 1000 + durationInSeconds;
		String expireHex = Long.toHexString(timestampNow);
		String toSignStr = String.format("%s%s%s", encryptKey, path, expireHex);
		String signedStr = md5ToLower(toSignStr);
		String signedUrl = null;
		if (urlObj.getQuery() != null) {
			signedUrl = String.format("%s&sign=%s&t=%s", url, signedStr, expireHex);
		} else {
			signedUrl = String.format("%s?sign=%s&t=%s", url, signedStr, expireHex);
		}
		return signedUrl;
	}

	private static String md5ToLower(String src) throws UnsupportedEncodingException, NoSuchAlgorithmException {
		MessageDigest digest = MessageDigest.getInstance("MD5");
		digest.update(src.getBytes("utf-8"));
		byte[] md5Bytes = digest.digest();
		return Hex.encodeHexString(md5Bytes);
	}

	public static void main(String args[]) throws Exception {
		// 页面上显示的key
		String encryptKey = "528a739baa990eaa19a9949a77a986ba1eabe18a";
		String encryptKey2 = "dd896ba86598108a2489ec89a6b9cea8aab8dd8a";
		//http://www.shituzx.com/o_1cbu2639h1hifvfl1bp11kk711kbh.mp4
		// 空间内资源的名称
		String fileKey = "o_1cbu2639h1hifvfl1bp11kk711kbh.mp4";
		try {
			// 您空间绑定的域名
			String urlToSign = String.format("http://www.shituzx.com/%s", fileKey + "?avinfo");
			String urlToSign2 = String.format("http://www.shituzx.com/o_1cbu2639h1hifvfl1bp11kk711kbh.mp4?avinfo");
			// 有效期
			int duration = 360000;
			String signedUrl = getAntiLeechAccessUrlBasedOnTimestamp(urlToSign2, encryptKey, duration);
			System.out.println(signedUrl);
		} catch (UnsupportedEncodingException e) {
			// http://hktry01.hktry.top/%E5%98%BF%E5%98%BF.jpeg?sign=6562a9f391e48b3a26ca509b21b5e695&t=59e9a35d 

			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	
	
}
